package redis

import (
	"fmt"
	"github.com/go-redis/redis"
	"go.uber.org/zap"
	"purchase-mall/conf"
	"purchase-mall/utils"
	"strconv"
	"strings"
	"time"
)

var (
	client *redis.Client
	Nil    = redis.Nil
)

// Init 初始化连接
func Init(cfg *conf.RedisConfig) (err error) {
	//fmt.Printf("Redis Switch %v\n", cfg.Switch)
	if cfg.Switch == false {
		return nil
	}

	client = redis.NewClient(&redis.Options{
		Addr:         fmt.Sprintf("%s:%d", cfg.Host, cfg.Port),
		Password:     cfg.Password, // no password set
		DB:           cfg.DB,       // use default DB
		PoolSize:     cfg.PoolSize,
		MinIdleConns: cfg.MinIdleConns,
	})

	_, err = client.Ping().Result()
	if err != nil {

		return err
	}
	return nil
}

func Close() {
	_ = client.Close()
}

// GetAuth 获取redis中的authorization 其中key:dynamicAuthorization
func GetAuth(key string) (error, string) {
	v, err := client.Get(key).Result()
	if err != nil {
		zap.L().Error("redis select AccessTotal err",
			zap.String("key", key),
			zap.Error(err))
		return err, ""
	}

	if err != nil {
		return err, ""
	}

	return nil, v
}

func IsBlock(token string) bool {
	statusCmd := client.Get(token)

	s := statusCmd.Val()

	status := strings.Contains(s, "block")

	return status
}

// access total
func SetAccessTotal(k string, v int64) {
	nanSecond := utils.TodayTime() - time.Now().UnixNano()
	t := time.Duration(nanSecond) * time.Nanosecond
	err := client.Set(k, v, t).Err()
	if err != nil {
		zap.L().Error("redis set AccessTotal err",
			zap.String("key", k),
			zap.Int64("value", v),
			zap.Error(err))
		return
	}
	return
}

func GetAccessTotal(key string) (error, int64) {
	v, err := client.Get(key).Result()
	if err != nil {
		zap.L().Error("redis select AccessTotal err",
			zap.String("key", key),
			zap.Error(err))
		return err, 0
	}

	vint, err := strconv.Atoi(v)
	if err != nil {
		return err, 0
	}

	return nil, int64(vint)
}

// peak value
func SetPeakValue(k string, v string) {
	//k=time v=fivetime+peakvalue
	nanSecond := utils.TodayTime() - time.Now().UnixNano()
	t := time.Duration(nanSecond) * time.Nanosecond

	err := client.Set(k, v, t).Err()
	if err != nil {
		zap.L().Error("redis set PeakValue err",
			zap.String("key", k),
			zap.String("value", v),
			zap.Error(err))
		return
	}
	return
}

func GetPeakValue(k string) (error, string) {
	v, err := client.Get(k).Result()

	if err != nil {
		zap.L().Error("redis select PeakValue err",
			zap.String("key", k),
			zap.Error(err))
		return err, ""
	}
	return nil, v
}
